package com.ciaojian.bytedance.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciaojian.core.bytedance.auth.ByteDanceTokenProvider;
import com.ciaojian.bytedance.vo.UrlVo;
import com.ciaojian.bytedance.vo.bytedance.*;
import com.ciaojian.core.bytedance.ByteDanceConfig;
import com.ciaojian.core.mapper.DyGoodsMapper;
import com.ciaojian.core.mapper.DyPoiMapper;
import com.ciaojian.core.model.dy.DyGoods;
import com.ciaojian.core.model.dy.DyPoi;
import com.ciaojian.core.util.JsonUtil;
import com.ciaojian.core.util.Result;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ByteDanceGoodsService {

    @Autowired
    private ByteDanceTokenProvider byteDanceTokenProvider;
    @Resource
    private DyGoodsMapper dyGoodsMapper;
    @Resource
    private DyPoiMapper dyPoiMapper;

    public JSONObject saveGoodsInfo(ProductSavaOrUpdateVo productSavaOrUpdateVo) {
        String bytedance_clienttoken = byteDanceTokenProvider.getBytedanceClienttoken("BYTEDANCE_CLIENTTOKEN");

        JSONObject param = new JSONObject();
        param.put("product", productSavaOrUpdateVo.getProduct());
        param.put("sku", productSavaOrUpdateVo.getSku());
        //定义接收数据
        JSONObject result = new JSONObject();
        try{
            HttpPost httpPost = new HttpPost(ByteDanceConfig.PRODUCT_SAVE_URL+bytedance_clienttoken);
            CloseableHttpClient client = HttpClients.createDefault();
            StringEntity entity = new StringEntity(param.toString(), "UTF-8");

            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);

            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode msgNode = objectMapper.readTree(productSavaOrUpdateVo.getProduct().getAttr_key_value_map().getImage_list());
            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));

                ByteSaveGoodsVo byteSaveGoodsVo = result.toJavaObject(ByteSaveGoodsVo.class);
                if (ObjectUtil.isNotNull(byteSaveGoodsVo.getData().getProduct_id())&& !"".equals(byteSaveGoodsVo.getData().getProduct_id())){
                    QueryWrapper<DyGoods> dyGoodsQueryWrapper = new QueryWrapper<>();
                    dyGoodsQueryWrapper.eq("dy_goods_id",byteSaveGoodsVo.getData().getProduct_id());
                    DyGoods dyGoods = dyGoodsMapper.selectOne(dyGoodsQueryWrapper);
                    if (ObjectUtil.isNotNull(dyGoods)){
                        dyGoods.setDyGoodsId(byteSaveGoodsVo.getData().getProduct_id());
                        dyGoods.setGoodsTitle(productSavaOrUpdateVo.getProduct().getProduct_name());
                        dyGoods.setCouponId(productSavaOrUpdateVo.getProduct().getConponId());
                        dyGoods.setUpdateTime(new Date());
                        long oldStartTime = (long) productSavaOrUpdateVo.getProduct().getSold_end_time()*1000L;
                        long soldEndTime = (long)productSavaOrUpdateVo.getProduct().getSold_end_time() * 1000L;
                        dyGoods.setSoldStartTime(new Date(oldStartTime));
                        dyGoods.setStatus(1);
                        dyGoods.setSoldEndTime(new Date(soldEndTime));
                        //封面图
                        List<JsonNode> imageList = msgNode.findParents("url");
                        JsonNode jsonNode = imageList.get(0);
                        String url = jsonNode.get("url").asText();
                        dyGoods.setPicture(url);
                        dyGoods.setAmount((long)productSavaOrUpdateVo.getSku().getActual_amount());
                        dyGoods.setStatus(1);
                        dyGoodsMapper.updateById(dyGoods);
                    }else {
                        DyGoods dyGoodsNew = new DyGoods();
                        dyGoodsNew.setDyGoodsId(byteSaveGoodsVo.getData().getProduct_id());
                        dyGoodsNew.setGoodsTitle(productSavaOrUpdateVo.getProduct().getProduct_name());
                        dyGoodsNew.setCouponId(productSavaOrUpdateVo.getProduct().getConponId());
                        dyGoodsNew.setAddTime(new Date());
                        dyGoodsNew.setUpdateTime(new Date());
                        long oldStartTime = (long) productSavaOrUpdateVo.getProduct().getSold_end_time()*1000L;
                        long soldEndTime = (long)productSavaOrUpdateVo.getProduct().getSold_end_time() * 1000L;
                        dyGoodsNew.setSoldStartTime(new Date(oldStartTime));
                        dyGoodsNew.setStatus(1);
                        dyGoodsNew.setSoldEndTime(new Date(soldEndTime));
                        List<JsonNode> imageList = msgNode.findParents("url");
                        JsonNode jsonNode = imageList.get(0);
                        String url = jsonNode.get("url").asText();
                        dyGoodsNew.setPicture(url);
                        dyGoodsNew.setAmount((long)productSavaOrUpdateVo.getSku().getActual_amount());
                        dyGoodsNew.setStatus(1);
                        dyGoodsMapper.insert(dyGoodsNew);
                    }
                }
            }

            return result;

        }catch (Exception e){
            return result;
        }
    }

    public JSONObject updateGoodsInfo(ProductUpdateVo productUpdateVo) throws Exception {
        //定义接收数据
        JSONObject result = new JSONObject();

        QueryWrapper<DyGoods> dyGoodsQueryWrapper = new QueryWrapper<>();
        dyGoodsQueryWrapper.eq("dy_goods_id",productUpdateVo.getProductId());
        DyGoods dyGoods = dyGoodsMapper.selectOne(dyGoodsQueryWrapper);
        if (ObjectUtil.isNull(dyGoods)){
            throw new Exception("数据库无产品");
        }


        ProductSavaOrUpdateVo.ProductBean productBean = new ProductSavaOrUpdateVo.ProductBean();
        ProductSavaOrUpdateVo.SkuBean sku = new ProductSavaOrUpdateVo.SkuBean();

        productBean.setCategory_full_name("丽人·美发·美发");
        productBean.setProduct_name(productUpdateVo.getProductName());
        productBean.setProduct_id(productUpdateVo.getProductId());
        productBean.setConponId(469);
        productBean.setSold_start_time(productUpdateVo.getStartDate());
        productBean.setSold_end_time(productUpdateVo.getEndDate());
        productBean.setProduct_type(1);
        productBean.setCategory_id(17001001);
        productBean.setAccount_name("广州潮剪企业发展有限公司");
        productBean.setBiz_line(5);
        productBean.setOut_url("{\"params\":\"{}\",\"path\":\"pages/index/index\",\"app_id\":\"tte9689fd5765669a801\"}");

        List<ProductSavaOrUpdateVo.ProductBean.PoiListBean> poiListBeans = new ArrayList<>();
        QueryWrapper<DyPoi> dyPoiQueryWrapper = new QueryWrapper<>();
        dyPoiQueryWrapper.eq("status", 1);
        List<DyPoi> dyPois = dyPoiMapper.selectList(dyPoiQueryWrapper);

        for (DyPoi pois : dyPois) {
            ProductSavaOrUpdateVo.ProductBean.PoiListBean poiListBean = new ProductSavaOrUpdateVo.ProductBean.PoiListBean();
            poiListBean.setPoi_id(pois.getPoiId());
            poiListBean.setSupplier_ext_id(pois.getStoreId().toString());
            poiListBeans.add(poiListBean);
        }
        productBean.setPoi_list(poiListBeans);

        ProductSavaOrUpdateVo.ProductBean.AttrKeyValueMapBean attrKeyValueMapBean = new ProductSavaOrUpdateVo.ProductBean.AttrKeyValueMapBean();
        attrKeyValueMapBean.setCan_no_use_date("{\"enable\":false}");
        attrKeyValueMapBean.setUse_time("{\"use_time_type\":1}");
        attrKeyValueMapBean.setReal_name_info("{\"enable\":false,\"scene\":0}");
        attrKeyValueMapBean.setAppointment("{\"need_appointment\":false,\"ahead_time_type\":1}");
        attrKeyValueMapBean.setSuperimposed_discounts("false");
        attrKeyValueMapBean.setAuto_renew("true");
        attrKeyValueMapBean.setRec_person_num("1");
        attrKeyValueMapBean.setLimit_gender("0");
        attrKeyValueMapBean.setRefundPolicy("3");
        attrKeyValueMapBean.setDescription("[]");
        attrKeyValueMapBean.setLimit_hair_length("0");
        attrKeyValueMapBean.setRefund_need_merchant_confirm("true");
        attrKeyValueMapBean.setEntryType("2");
        attrKeyValueMapBean.setNotification("[{\"title\":\"使用规则\",\"content\":\"到店出示使用\"}]");
        attrKeyValueMapBean.setDescription_rich_text("[{\"note_type\":1," +
                "\"content\":\""+productUpdateVo.getText()+"\"}]");

        List<UrlVo> urlVos = new ArrayList<>();
        List<String> envImageList = productUpdateVo.getEnvImageList();
        for (String s : envImageList) {
            UrlVo urlVo = new UrlVo();
            urlVo.setUrl(s);
            urlVos.add(urlVo);
        }
        attrKeyValueMapBean.setEnvironment_image_list(JsonUtil.toJson(urlVos));
        attrKeyValueMapBean.setShow_channel("1");
        attrKeyValueMapBean.setOriginal_vip_can_experience("0");
        attrKeyValueMapBean.setDetail_image_list(JsonUtil.toJson(urlVos));
        attrKeyValueMapBean.setCustomer_reserved_info("{\"allow\":true,\"allow_tel\":true}");

        List<UrlVo> urlImgVos = new ArrayList<>();
        List<String> imageList = productUpdateVo.getImageList();
        for (String s : imageList) {
            UrlVo urlVo = new UrlVo();
            urlVo.setUrl(s);
            urlImgVos.add(urlVo);
        }
        attrKeyValueMapBean.setImage_list(JsonUtil.toJson(urlImgVos));
        attrKeyValueMapBean.setUse_date("{\"use_date_type\":2,\"day_duration\":15,\"use_start_date\":\"\",\"use_end_date\":\"\",\"days_of_week\":null}");

        productBean.setAttr_key_value_map(attrKeyValueMapBean);

        sku.setOrigin_amount(productUpdateVo.getOriginAmount());
        sku.setActual_amount(productUpdateVo.getActualAmount());
        sku.setSku_id(productUpdateVo.getProductId());
        sku.setSku_name(productUpdateVo.getProductName());

        ProductSavaOrUpdateVo.SkuBean.StockBean stockBean = new ProductSavaOrUpdateVo.SkuBean.StockBean();
        stockBean.setLimit_type(2);
        stockBean.setStock_qty(10000000000L);

        sku.setStock(stockBean);

        ProductSavaOrUpdateVo.SkuBean.AttrKeyValueMapBeanX attrKeyValueMapBeanX = new ProductSavaOrUpdateVo.SkuBean.AttrKeyValueMapBeanX();
        attrKeyValueMapBeanX.setTake_rate("60");
        attrKeyValueMapBeanX.setCommodity("[{\"group_name\":\"剪发券\",\"total_count\":1," +
                "\"option_count\":1,\"item_list\":[{\"name\":\""+productUpdateVo.getProductName()+"\",\"price\":"+productUpdateVo.getOriginAmount()+",\"count\":1," +
                "\"unit\":\"份\"}]}]");
        attrKeyValueMapBeanX.setSettle_type("1");
        attrKeyValueMapBeanX.setUse_type("1");
        attrKeyValueMapBeanX.setRefund_need_merchant_confirm("true");
        attrKeyValueMapBeanX.setRefund_type("[\"过期退款\",\"随时退款\"]");
        attrKeyValueMapBeanX.setCode_source_type("1");
        attrKeyValueMapBeanX.setLimit_rule("{\"is_limit\":true,\"total_buy_num\":1}");
        sku.setAttr_key_value_map(attrKeyValueMapBeanX);
        sku.setStatus(1);
        ProductSavaOrUpdateVo productSavaOrUpdateVo = new ProductSavaOrUpdateVo();
        productSavaOrUpdateVo.setProduct(productBean);
        productSavaOrUpdateVo.setSku(sku);


        String bytedance_clienttoken = byteDanceTokenProvider.getBytedanceClienttoken("BYTEDANCE_CLIENTTOKEN");

        JSONObject param = new JSONObject();
        param.put("product", productSavaOrUpdateVo.getProduct());
        param.put("sku", productSavaOrUpdateVo.getSku());
        try{
            HttpPost httpPost = new HttpPost(ByteDanceConfig.PRODUCT_SAVE_URL+bytedance_clienttoken);
            CloseableHttpClient client = HttpClients.createDefault();
            StringEntity entity = new StringEntity(param.toString(), "UTF-8");

            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);

            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));

                ByteSaveGoodsVo byteSaveGoodsVo = result.toJavaObject(ByteSaveGoodsVo.class);
                if (ObjectUtil.isNotNull(byteSaveGoodsVo.getData().getProduct_id())){

                    dyGoods.setDyGoodsId(productUpdateVo.getProductId());
                    dyGoods.setGoodsTitle(productBean.getProduct_name());
                    dyGoods.setCouponId(productBean.getConponId());
                    dyGoods.setUpdateTime(new Date());
                    long oldStartTime = (long) productUpdateVo.getStartDate()*1000L;
                    long soldEndTime = (long)productUpdateVo.getEndDate() * 1000L;
                    dyGoods.setSoldStartTime(new Date(oldStartTime));
                    dyGoods.setSoldEndTime(new Date(soldEndTime));
                    dyGoods.setStatus(1);
                    //封面图

                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode msgNode = objectMapper.readTree(productBean.getAttr_key_value_map().getImage_list());

                    List<JsonNode> imageLists = msgNode.findParents("url");
                    JsonNode jsonNode = imageLists.get(0);
                    String url = jsonNode.get("url").asText();
                    dyGoods.setPicture(url);
                    dyGoods.setAmount((long)sku.getActual_amount());
                    dyGoods.setStatus(1);
                    dyGoodsMapper.updateById(dyGoods);
                }
            }

            return result;

        }catch (Exception e){
            return result;
        }
    }

    /**
     * 免审核修改商品
     */
    public JSONObject savefreeaudit(String productId, String soldEndtime, String stockQty) throws ParseException {
        String bytedance_clienttoken = byteDanceTokenProvider.getBytedanceClienttoken("BYTEDANCE_CLIENTTOKEN");

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = dateFormat.parse(soldEndtime);

        JSONObject param = new JSONObject();
        param.put("product_id", productId);
        param.put("sold_end_time", parse.getTime()/1000);
        param.put("stock_qty", stockQty);
        //定义接收数据
        JSONObject result = new JSONObject();
        try{
            HttpPost httpPost = new HttpPost(ByteDanceConfig.PRODUCT_FREE_AUDIT+bytedance_clienttoken);
            CloseableHttpClient client = HttpClients.createDefault();
            StringEntity entity = new StringEntity(param.toString(), "UTF-8");

            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);

            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
            }
            return result;

        }catch (Exception e){
            return result;
        }
    }

    /**
     * 获取抖音商品模板
     */
    public JSONObject getgoodstemplate(String categoryId, String productType) {
        String bytedance_clienttoken = byteDanceTokenProvider.getBytedanceClienttoken("BYTEDANCE_CLIENTTOKEN");

        //定义接收数据
        JSONObject result = new JSONObject();

        try{
            HttpGet httpGet = new HttpGet(ByteDanceConfig.GOODS_TEMPLATE_URL+bytedance_clienttoken+"&category_id="+categoryId+"&product_type="+productType);
            CloseableHttpClient client = HttpClients.createDefault();

            HttpResponse response = client.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
            }
            return result;

        }catch (Exception e){
            return result;
        }
    }

    /**
     * 查询商品线上数据列表
     */
    public Result productList(String cursor, int count, int status) {
        String bytedance_clienttoken = byteDanceTokenProvider.getBytedanceClienttoken("BYTEDANCE_CLIENTTOKEN");

        //定义接收数据
        JSONObject result = new JSONObject();

        try{
            String url = ByteDanceConfig.GOODS_LIST_URL+bytedance_clienttoken+"&status="+status+"&count="+count+"&cursor=" + cursor;

            HttpGet httpGet = new HttpGet(url);
            CloseableHttpClient client = HttpClients.createDefault();

            HttpResponse response = client.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
            }

            ByteDanceProductVo byteDanceProductVo = new ByteDanceProductVo();
            List<ByteDanceProductVo.ProductOnlineListBean> productList = new ArrayList<>();

            GoodsList goodsList = result.toJavaObject(GoodsList.class);

            byteDanceProductVo.setHas_more(goodsList.getData().isHas_more());
            byteDanceProductVo.setNext_cursor(goodsList.getData().getNext_cursor());

            List<GoodsList.DataBean.ProductListBean> product_list = goodsList.getData().getProduct_list();
            for (GoodsList.DataBean.ProductListBean productOnlineListBean : product_list) {

                ByteDanceProductVo.ProductOnlineListBean product = new ByteDanceProductVo.ProductOnlineListBean();
                ByteDanceProductVo.ProductOnlineListBean.ProductBean productBean = new ByteDanceProductVo.ProductOnlineListBean.ProductBean();


                productBean.setCategory_full_name(productOnlineListBean.getProduct().getCategory_full_name());
                productBean.setCreate_time(productOnlineListBean.getProduct().getCreate_time());
//                productBean.setCreator_account_id(productOnlineListBean.getProduct().getCreator_account_id());
                productBean.setOwner_account_id(productOnlineListBean.getProduct().getOwner_account_id());
                productBean.setProduct_name(productOnlineListBean.getProduct().getProduct_name());
                productBean.setProduct_id(productOnlineListBean.getProduct().getProduct_id());

                ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean attr_key_value_map = new ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean();
                String can_no_use_date = productOnlineListBean.getProduct().getAttr_key_value_map().getCan_no_use_date();
                ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.CanNoUseDateBaen canNoUseDateBaen = JsonUtil.fromJson(can_no_use_date, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.CanNoUseDateBaen.class);



                attr_key_value_map.setCan_no_use_date(canNoUseDateBaen);


                attr_key_value_map.setAuto_renew(productOnlineListBean.getProduct().getAttr_key_value_map().getAuto_renew());
                attr_key_value_map.setShow_channel(productOnlineListBean.getProduct().getAttr_key_value_map().getShow_channel());
                attr_key_value_map.setSubTitle(productOnlineListBean.getProduct().getAttr_key_value_map().getSubTitle());

                String use_time = productOnlineListBean.getProduct().getAttr_key_value_map().getUse_time();
                ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.UseTimeBaen useTimeBaen = JsonUtil.fromJson(use_time, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.UseTimeBaen.class);
                attr_key_value_map.setUse_time(useTimeBaen);

                String real_name_info = productOnlineListBean.getProduct().getAttr_key_value_map().getReal_name_info();
                ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.RealNameInfoBaen realNameInfoBaen = JsonUtil.fromJson(real_name_info, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.RealNameInfoBaen.class);
                attr_key_value_map.setReal_name_info(realNameInfoBaen);

                String appointment = productOnlineListBean.getProduct().getAttr_key_value_map().getAppointment();
                ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.AppointmentBean appointmentBean = JsonUtil.fromJson(appointment, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.AppointmentBean.class);
                attr_key_value_map.setAppointment(appointmentBean);

                String description_rich_text = productOnlineListBean.getProduct().getAttr_key_value_map().getDescription_rich_text();
                List<ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.DescriptionRichTextBaen> descriptionRichTextBaens = JSONArray.parseArray(description_rich_text, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.DescriptionRichTextBaen.class);
                attr_key_value_map.setDescription_rich_text(descriptionRichTextBaens);

                String environment_image_list = productOnlineListBean.getProduct().getAttr_key_value_map().getEnvironment_image_list();
                List<ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.EnvironmentImageListBaen> environmentImageListBaens = JSONArray.parseArray(environment_image_list, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.EnvironmentImageListBaen.class);
                attr_key_value_map.setEnvironment_image_list(environmentImageListBaens);

                String customer_reserved_info = productOnlineListBean.getProduct().getAttr_key_value_map().getCustomer_reserved_info();
                ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.CustomerReservedInfoBaen customerReservedInfoBaen = JsonUtil.fromJson(customer_reserved_info, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.CustomerReservedInfoBaen.class);
                attr_key_value_map.setCustomer_reserved_info(customerReservedInfoBaen);

                String image_list = productOnlineListBean.getProduct().getAttr_key_value_map().getImage_list();
                List<ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.ImageListBean> imageListBeans = JSONArray.parseArray(image_list, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.ImageListBean.class);
                attr_key_value_map.setImage_list(imageListBeans);

                String use_date = productOnlineListBean.getProduct().getAttr_key_value_map().getUse_date();
                ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.UseDateBean useDateBean = JsonUtil.fromJson(use_date, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.UseDateBean.class);
                attr_key_value_map.setUse_date(useDateBean);

                productBean.setAttr_key_value_map(attr_key_value_map);
                productBean.setSold_end_time(productOnlineListBean.getProduct().getSold_end_time());
                productBean.setUpdate_time(productOnlineListBean.getProduct().getUpdate_time());
                productBean.setProduct_type(productOnlineListBean.getProduct().getProduct_type());
                productBean.setCategory_id(productOnlineListBean.getProduct().getCategory_id());
                productBean.setSold_start_time(productOnlineListBean.getProduct().getSold_start_time());
                productBean.setAccount_name(productOnlineListBean.getProduct().getAccount_name());
                productBean.setProduct_id(productOnlineListBean.getProduct().getProduct_id());
                productBean.setBiz_line(productOnlineListBean.getProduct().getBiz_line());
                String s = JsonUtil.toJson(productOnlineListBean.getProduct().getPoi_list());
                List<ByteDanceProductVo.ProductOnlineListBean.ProductBean.PoiListBean> poiListBeans = JSONArray.parseArray(s, ByteDanceProductVo.ProductOnlineListBean.ProductBean.PoiListBean.class);


                productBean.setPoi_list(poiListBeans);
                product.setProduct(productBean);
                product.setOnline_status(productOnlineListBean.getOnline_status());

                String s1 = JsonUtil.toJson(productOnlineListBean.getCommission_info());
                ByteDanceProductVo.ProductOnlineListBean.CommissionInfoBean commissionInfoBean = JsonUtil.fromJson(s1, ByteDanceProductVo.ProductOnlineListBean.CommissionInfoBean.class);
                product.setCommission_info(commissionInfoBean);

                ByteDanceProductVo.ProductOnlineListBean.SkuBean skuBean = new ByteDanceProductVo.ProductOnlineListBean.SkuBean();
                skuBean.setUpdate_time(productOnlineListBean.getSku().getUpdate_time());
                skuBean.setOrigin_amount(productOnlineListBean.getSku().getOrigin_amount());
                skuBean.setCreate_time(productOnlineListBean.getSku().getCreate_time());
                skuBean.setActual_amount(productOnlineListBean.getSku().getActual_amount());
                skuBean.setSku_id(productOnlineListBean.getSku().getSku_id());
                skuBean.setSku_name(productOnlineListBean.getSku().getSku_name());
                ByteDanceProductVo.ProductOnlineListBean.SkuBean.StockBean stockBean = new ByteDanceProductVo.ProductOnlineListBean.SkuBean.StockBean();
                stockBean.setLimit_type(productOnlineListBean.getSku().getStock().getLimit_type());
                stockBean.setStock_qty(productOnlineListBean.getSku().getStock().getStock_qty());
                skuBean.setStock(stockBean);

                ByteDanceProductVo.ProductOnlineListBean.SkuBean.AttrKeyValueMapBeanX attrKeyValueMapBeanX = new ByteDanceProductVo.ProductOnlineListBean.SkuBean.AttrKeyValueMapBeanX ();


                String commodity = productOnlineListBean.getSku().getAttr_key_value_map().getCommodity();
                List<ByteDanceProductVo.ProductOnlineListBean.SkuBean.AttrKeyValueMapBeanX.CommodityBean> commodityBeans = JSONArray.parseArray(commodity, ByteDanceProductVo.ProductOnlineListBean.SkuBean.AttrKeyValueMapBeanX.CommodityBean.class);
                attrKeyValueMapBeanX.setCommodity(commodityBeans);

                attrKeyValueMapBeanX.setSettle_type(productOnlineListBean.getSku().getAttr_key_value_map().getSettle_type());
                attrKeyValueMapBeanX.setUse_type(productOnlineListBean.getSku().getAttr_key_value_map().getUse_type());


                attrKeyValueMapBeanX.setCode_source_type(productOnlineListBean.getSku().getAttr_key_value_map().getCode_source_type());


                String limit_rule = productOnlineListBean.getSku().getAttr_key_value_map().getLimit_rule();
                ByteDanceProductVo.ProductOnlineListBean.SkuBean.AttrKeyValueMapBeanX.LimitRuleBean limitRuleBean = JsonUtil.fromJson(limit_rule, ByteDanceProductVo.ProductOnlineListBean.SkuBean.AttrKeyValueMapBeanX.LimitRuleBean.class);
                attrKeyValueMapBeanX.setLimit_rule(limitRuleBean);

                skuBean.setAttr_key_value_map(attrKeyValueMapBeanX);
                skuBean.setStatus(productOnlineListBean.getSku().getStatus());

                product.setSku(skuBean);

                productList.add(product);
            }

            byteDanceProductVo.setProduct_online_list(productList);

            return Result.ok(byteDanceProductVo);

        }catch (Exception e){

            return Result.ok(e.getMessage());
        }
    }

    /**
     * 查询商品线上数据(抖音原数据
     * @param productIds
     * @param outIds
     * @return
     */
    public JSONObject productOneGet(String productIds, String outIds) {
        String bytedance_clienttoken = byteDanceTokenProvider.getBytedanceClienttoken("BYTEDANCE_CLIENTTOKEN");

        //定义接收数据
        JSONObject result = new JSONObject();

        try{
            HttpGet httpGet = new HttpGet(ByteDanceConfig.GOODS_GET_URL+bytedance_clienttoken+"&product_ids="+productIds+"&out_ids="+outIds);
            CloseableHttpClient client = HttpClients.createDefault();

            HttpResponse response = client.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
            }

            return result;

        }catch (Exception e){
            return result;
        }
    }

    /**
     * 查询商品线上数据
     * @param productIds
     * @param outIds
     * @return
     */
    public Result productGet(String productIds, String outIds) {
        String bytedance_clienttoken = byteDanceTokenProvider.getBytedanceClienttoken("BYTEDANCE_CLIENTTOKEN");

        //定义接收数据
        JSONObject result = new JSONObject();

        try{
            HttpGet httpGet = new HttpGet(ByteDanceConfig.GOODS_GET_URL+bytedance_clienttoken+"&product_ids="+productIds+"&out_ids="+outIds);
            CloseableHttpClient client = HttpClients.createDefault();

            HttpResponse response = client.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
            }

            ByteDanceGoodsGetVo byteDanceGoodsGetVo = result.toJavaObject(ByteDanceGoodsGetVo.class);


            ByteDanceProductVo byteDanceProductVo = new ByteDanceProductVo();
            List<ByteDanceProductVo.ProductOnlineListBean> productList = new ArrayList<>();
            ByteDanceProductVo.ProductOnlineListBean product = new ByteDanceProductVo.ProductOnlineListBean();


            List<ByteDanceGoodsGetVo.DataBean.ProductOnlineListBean> product_online_list = byteDanceGoodsGetVo.getData().getProduct_online_list();
            for (ByteDanceGoodsGetVo.DataBean.ProductOnlineListBean productOnlineListBean : product_online_list) {

                ByteDanceProductVo.ProductOnlineListBean.ProductBean productBean = new ByteDanceProductVo.ProductOnlineListBean.ProductBean();
                productBean.setCategory_full_name(productOnlineListBean.getProduct().getCategory_full_name());
                productBean.setCreate_time(productOnlineListBean.getProduct().getCreate_time());
                productBean.setCreator_account_id(productOnlineListBean.getProduct().getCreator_account_id());
                productBean.setOwner_account_id(productOnlineListBean.getProduct().getOwner_account_id());
                productBean.setProduct_name(productOnlineListBean.getProduct().getProduct_name());

                QueryWrapper<DyGoods> dyGoodsQueryWrapper = new QueryWrapper<>();
                dyGoodsQueryWrapper.eq("dy_goods_id",productIds);
                DyGoods dyGoods = dyGoodsMapper.selectOne(dyGoodsQueryWrapper);
                productBean.setServe_notice(dyGoods.getServeNotice());

                ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean attr_key_value_map = new ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean();
                String can_no_use_date = productOnlineListBean.getProduct().getAttr_key_value_map().getCan_no_use_date();
                ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.CanNoUseDateBaen canNoUseDateBaen = JsonUtil.fromJson(can_no_use_date, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.CanNoUseDateBaen.class);

                attr_key_value_map.setCan_no_use_date(canNoUseDateBaen);


                attr_key_value_map.setSuperimposed_discounts(productOnlineListBean.getProduct().getAttr_key_value_map().getSuperimposed_discounts());
                attr_key_value_map.setAuto_renew(productOnlineListBean.getProduct().getAttr_key_value_map().getAuto_renew());
                attr_key_value_map.setRec_person_num(productOnlineListBean.getProduct().getAttr_key_value_map().getRec_person_num());
                attr_key_value_map.setShow_channel(productOnlineListBean.getProduct().getAttr_key_value_map().getShow_channel());

                String use_time = productOnlineListBean.getProduct().getAttr_key_value_map().getUse_time();
                ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.UseTimeBaen useTimeBaen = JsonUtil.fromJson(use_time, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.UseTimeBaen.class);
                attr_key_value_map.setUse_time(useTimeBaen);

                String real_name_info = productOnlineListBean.getProduct().getAttr_key_value_map().getReal_name_info();
                ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.RealNameInfoBaen realNameInfoBaen = JsonUtil.fromJson(real_name_info, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.RealNameInfoBaen.class);
                attr_key_value_map.setReal_name_info(realNameInfoBaen);

                String appointment = productOnlineListBean.getProduct().getAttr_key_value_map().getAppointment();
                ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.AppointmentBean appointmentBean = JsonUtil.fromJson(appointment, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.AppointmentBean.class);
                attr_key_value_map.setAppointment(appointmentBean);

                String description_rich_text = productOnlineListBean.getProduct().getAttr_key_value_map().getDescription_rich_text();
                List<ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.DescriptionRichTextBaen> descriptionRichTextBaens = JSONArray.parseArray(description_rich_text, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.DescriptionRichTextBaen.class);
                attr_key_value_map.setDescription_rich_text(descriptionRichTextBaens);

                String environment_image_list = productOnlineListBean.getProduct().getAttr_key_value_map().getEnvironment_image_list();
                List<ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.EnvironmentImageListBaen> environmentImageListBaens = JSONArray.parseArray(environment_image_list, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.EnvironmentImageListBaen.class);
                attr_key_value_map.setEnvironment_image_list(environmentImageListBaens);

                String customer_reserved_info = productOnlineListBean.getProduct().getAttr_key_value_map().getCustomer_reserved_info();
                ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.CustomerReservedInfoBaen customerReservedInfoBaen = JsonUtil.fromJson(customer_reserved_info, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.CustomerReservedInfoBaen.class);
                attr_key_value_map.setCustomer_reserved_info(customerReservedInfoBaen);

                String image_list = productOnlineListBean.getProduct().getAttr_key_value_map().getImage_list();
                List<ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.ImageListBean> imageListBeans = JSONArray.parseArray(image_list, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.ImageListBean.class);
                attr_key_value_map.setImage_list(imageListBeans);

                String use_date = productOnlineListBean.getProduct().getAttr_key_value_map().getUse_date();
                ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.UseDateBean useDateBean = JsonUtil.fromJson(use_date, ByteDanceProductVo.ProductOnlineListBean.ProductBean.AttrKeyValueMapBean.UseDateBean.class);
                attr_key_value_map.setUse_date(useDateBean);

                productBean.setAttr_key_value_map(attr_key_value_map);
                productBean.setSold_end_time(productOnlineListBean.getProduct().getSold_end_time());
                productBean.setUpdate_time(productOnlineListBean.getProduct().getUpdate_time());
                productBean.setProduct_type(productOnlineListBean.getProduct().getProduct_type());
                productBean.setCategory_id(productOnlineListBean.getProduct().getCategory_id());
                productBean.setSold_start_time(productOnlineListBean.getProduct().getSold_start_time());
                productBean.setAccount_name(productOnlineListBean.getProduct().getAccount_name());
                productBean.setProduct_id(productOnlineListBean.getProduct().getProduct_id());
                productBean.setBiz_line(productOnlineListBean.getProduct().getBiz_line());
                String s = JsonUtil.toJson(productOnlineListBean.getProduct().getPoi_list());
                List<ByteDanceProductVo.ProductOnlineListBean.ProductBean.PoiListBean> poiListBeans = JSONArray.parseArray(s, ByteDanceProductVo.ProductOnlineListBean.ProductBean.PoiListBean.class);


                productBean.setPoi_list(poiListBeans);
                product.setProduct(productBean);
                product.setOnline_status(productOnlineListBean.getOnline_status());

                String s1 = JsonUtil.toJson(productOnlineListBean.getCommission_info());
                ByteDanceProductVo.ProductOnlineListBean.CommissionInfoBean commissionInfoBean = JsonUtil.fromJson(s1, ByteDanceProductVo.ProductOnlineListBean.CommissionInfoBean.class);
                product.setCommission_info(commissionInfoBean);

                ByteDanceProductVo.ProductOnlineListBean.SkuBean skuBean = new ByteDanceProductVo.ProductOnlineListBean.SkuBean();
                skuBean.setUpdate_time(productOnlineListBean.getSku().getUpdate_time());
                skuBean.setOrigin_amount(productOnlineListBean.getSku().getOrigin_amount());
                skuBean.setCreate_time(productOnlineListBean.getSku().getCreate_time());
                skuBean.setActual_amount(productOnlineListBean.getSku().getActual_amount());
                skuBean.setSku_id(productOnlineListBean.getSku().getSku_id());
                skuBean.setSku_name(productOnlineListBean.getSku().getSku_name());
                ByteDanceProductVo.ProductOnlineListBean.SkuBean.StockBean stockBean = new ByteDanceProductVo.ProductOnlineListBean.SkuBean.StockBean();
                stockBean.setLimit_type(productOnlineListBean.getSku().getStock().getLimit_type());
                stockBean.setStock_qty(productOnlineListBean.getSku().getStock().getStock_qty());
                skuBean.setStock(stockBean);

                ByteDanceProductVo.ProductOnlineListBean.SkuBean.AttrKeyValueMapBeanX attrKeyValueMapBeanX = new ByteDanceProductVo.ProductOnlineListBean.SkuBean.AttrKeyValueMapBeanX ();
                attrKeyValueMapBeanX.setTake_rate(productOnlineListBean.getSku().getAttr_key_value_map().getTake_rate());


                String commodity = productOnlineListBean.getSku().getAttr_key_value_map().getCommodity();
                List<ByteDanceProductVo.ProductOnlineListBean.SkuBean.AttrKeyValueMapBeanX.CommodityBean> commodityBeans = JSONArray.parseArray(commodity, ByteDanceProductVo.ProductOnlineListBean.SkuBean.AttrKeyValueMapBeanX.CommodityBean.class);
                attrKeyValueMapBeanX.setCommodity(commodityBeans);

                attrKeyValueMapBeanX.setSettle_type(productOnlineListBean.getSku().getAttr_key_value_map().getSettle_type());
                attrKeyValueMapBeanX.setUse_type(productOnlineListBean.getSku().getAttr_key_value_map().getUse_type());
                attrKeyValueMapBeanX.setRefund_need_merchant_confirm(productOnlineListBean.getSku().getAttr_key_value_map().getRefund_need_merchant_confirm());

                String refund_type = productOnlineListBean.getSku().getAttr_key_value_map().getRefund_type();
                List<String> refundTypes = JSONArray.parseArray(refund_type, String.class);

                attrKeyValueMapBeanX.setRefund_type(refundTypes);


                String limit_buy_rule = productOnlineListBean.getSku().getAttr_key_value_map().getLimit_buy_rule();
                ByteDanceProductVo.ProductOnlineListBean.SkuBean.AttrKeyValueMapBeanX.LimitBuyRuleBean limitBuyRuleBean = JsonUtil.fromJson(limit_buy_rule, ByteDanceProductVo.ProductOnlineListBean.SkuBean.AttrKeyValueMapBeanX.LimitBuyRuleBean.class);
                attrKeyValueMapBeanX.setLimit_buy_rule(limitBuyRuleBean);

                attrKeyValueMapBeanX.setCode_source_type(productOnlineListBean.getSku().getAttr_key_value_map().getCode_source_type());


                String limit_rule = productOnlineListBean.getSku().getAttr_key_value_map().getLimit_rule();
                ByteDanceProductVo.ProductOnlineListBean.SkuBean.AttrKeyValueMapBeanX.LimitRuleBean limitRuleBean = JsonUtil.fromJson(limit_rule, ByteDanceProductVo.ProductOnlineListBean.SkuBean.AttrKeyValueMapBeanX.LimitRuleBean.class);
                attrKeyValueMapBeanX.setLimit_rule(limitRuleBean);

                skuBean.setAttr_key_value_map(attrKeyValueMapBeanX);
                skuBean.setStatus(productOnlineListBean.getSku().getStatus());

                product.setSku(skuBean);

                productList.add(product);
            }

            byteDanceProductVo.setProduct_online_list(productList);

            return Result.ok(byteDanceProductVo);

        }catch (Exception e){
            return Result.error("请求失败");
        }
    }

    /**
     * 查询商品草稿数据列表
     */
    public JSONObject productDraft() {
        String bytedance_clienttoken = byteDanceTokenProvider.getBytedanceClienttoken("BYTEDANCE_CLIENTTOKEN");

        //定义接收数据
        JSONObject result = new JSONObject();

        try{
            HttpGet httpGet = new HttpGet(ByteDanceConfig.GOODS_DRAFT_URL+bytedance_clienttoken);
            CloseableHttpClient client = HttpClients.createDefault();

            HttpResponse response = client.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));

            }
            return result;

        }catch (Exception e){
            return result;
        }
    }

    /**
     * 商品sku同步
     */
    public JSONObject syncStore(ByteDanceSyncGoodsSkuVo byteDanceSyncGoodsSkuVo) {
        String bytedance_clienttoken = byteDanceTokenProvider.getBytedanceClienttoken("BYTEDANCE_CLIENTTOKEN");

        JSONObject param = new JSONObject();
        param.put("skus", byteDanceSyncGoodsSkuVo.getSkus());
        param.put("spu_ext_id", byteDanceSyncGoodsSkuVo.getSpu_ext_id());
        JSONObject result = new JSONObject();

        try{
            HttpPost httpPost = new HttpPost(ByteDanceConfig.GOODS_SYNC_URL+bytedance_clienttoken);
            CloseableHttpClient client = HttpClients.createDefault();
            StringEntity entity = new StringEntity(param.toString(), "UTF-8");

            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);

            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
            }

            return result;

        }catch (Exception e){
            return result;
        }
    }

    public Result draftList(String productIds) {

        String bytedance_clienttoken = byteDanceTokenProvider.getBytedanceClienttoken("BYTEDANCE_CLIENTTOKEN");

        //定义接收数据
        JSONObject result = new JSONObject();

        try{
            HttpGet httpGet = new HttpGet(ByteDanceConfig.GOODS_DRAFT_GET+bytedance_clienttoken+"&product_ids="+productIds);
            CloseableHttpClient client = HttpClients.createDefault();

            HttpResponse response = client.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
            }


            return Result.ok(result);

        }catch (Exception e){

            return Result.ok(e.getMessage());
        }
    }

    public JSONObject operate(String productId, int type) {

        String bytedance_clienttoken = byteDanceTokenProvider.getBytedanceClienttoken("BYTEDANCE_CLIENTTOKEN");

        JSONObject param = new JSONObject();
        param.put("product_id", productId);
        param.put("op_type", type); //1上线 2下线
        JSONObject result = new JSONObject();

        try{
            HttpPost httpPost = new HttpPost(ByteDanceConfig.GOODS_PRODUCT_OPERATE+bytedance_clienttoken);
            CloseableHttpClient client = HttpClients.createDefault();
            StringEntity entity = new StringEntity(param.toString(), "UTF-8");

            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);

            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));

                QueryWrapper<DyGoods> dyGoodsQueryWrapper = new QueryWrapper<>();
                dyGoodsQueryWrapper.eq("dy_goods_id",productId);

                DyGoods dyGoods = new DyGoods().selectOne(dyGoodsQueryWrapper);

                dyGoods.setStatus(type);
                dyGoods.updateById();
            }

            return result;

        }catch (Exception e){
            return result;
        }
    }
}
